//
//  SingInDetailViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/12/2.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "SingInDetailViewController.h"
#import "SIgnInDetailListModel.h"
#import "SignInDetailTableViewCell.h"
#import "SignInExplainView.h"
#import "TaskDetailViewController.h"

#define getSigninOrSignoutList @"getSigninOrSignoutList"//签到详情列表

@interface SingInDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *_tableView;//列表
    SIgnInDetailListModel *_detailListModel;
    NSInteger _photoPageCount;//当前图片的页数
    NSInteger _photoNum;//照片的总数量
}
@end

@implementation SingInDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //[self setRightBackNavigation];
    [self setNavigationTitle:self.navaTitleStr];
    [self setLeftBackNavigation];
    [self getSigninOrSignoutListRequest];
    [self creatView];
    // Do any additional setup after loading the view.
}

#pragma mark - creatTableView
- (void)creatView{
    
    //列表
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,0, IPHONE_WIDTH, IPHONE_HEIGHT-64) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.backgroundColor=[UIColor clearColor];
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.showsHorizontalScrollIndicator=NO;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.bounces=NO;
    [self.view addSubview:_tableView];
    
}
#pragma mark -照片查看
- (void)photoImageView:(MyImageView *)imageView{
    [self creatPhotoViewWithPhotoUrl:imageView.urlStr address:imageView.nameStr time:imageView.timeStr];
}

#pragma mark -照片查看
- (void)creatPhotoViewWithPhotoUrl:(NSString *)photoUrl address:(NSString *)address time:(NSString *)time{
    _photoPageCount=0;
    UIButton *photoView=[MyControl creatButtonWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT) target:self sel:@selector(cancelPhotoClick:) tag:200 image:nil title:@""];
    photoView.backgroundColor=[UIColor clearColor];
    [[[UIApplication sharedApplication].delegate window] addSubview:photoView];
    
    //半透明的view
    UIView *alphaView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    alphaView.backgroundColor=[UIColor blackColor];
    alphaView.alpha=0.5;
    alphaView.userInteractionEnabled=NO;
    [photoView addSubview:alphaView];
    
    NSArray *infoArr=[photoUrl componentsSeparatedByString:@"|"];
    _photoNum=infoArr.count;
    //滚动视图
    UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, (IPHONE_HEIGHT-(IPHONE_WIDTH-40-60))/2, IPHONE_WIDTH, IPHONE_WIDTH-40-60)];
    scrollView.contentSize=CGSizeMake(IPHONE_WIDTH*infoArr.count, 0);
    scrollView.tag=180;
    scrollView.bounces=NO;
    scrollView.userInteractionEnabled=NO;
    scrollView.pagingEnabled=YES;
    scrollView.scrollEnabled=NO;
    [photoView addSubview:scrollView];
    for (int i=0; i<infoArr.count; i++) {
        //照片
        UIImageView *photo=[[UIImageView alloc]initWithFrame:CGRectMake(20+scrollView.width*i, 0, IPHONE_WIDTH-40, scrollView.height)];
        [photo setImageWithURL:[NSURL URLWithString:infoArr[i]] placeholderImage:[UIImage imageNamed:@"ic_pic_bg@2x"]];
        [scrollView addSubview:photo];
    }
    //如果不止一张图片 则添加向左向右按钮
    if (infoArr.count>1) {
        UIButton *leftButton=[MyControl creatButtonWithFrame:CGRectMake(5, scrollView.y+(scrollView.height-40)/2, 50, 50) target:self sel:@selector(leftPhotoClick:) tag:220 image:nil title:@""];
        [leftButton setImage:[UIImage imageNamed:@"jiantou_left@2x"] forState:UIControlStateNormal];
        leftButton.layer.masksToBounds=YES;
        leftButton.layer.cornerRadius=leftButton.width/2;
        leftButton.backgroundColor=[UIColor whiteColor];
        leftButton.hidden=YES;
        leftButton.alpha=0.8;
        [photoView addSubview:leftButton];
        
        UIButton *rightButton=[MyControl creatButtonWithFrame:CGRectMake(IPHONE_WIDTH-5-50,scrollView.y+(scrollView.height-50)/2, 50, 50) target:self sel:@selector(rightPhotoClick:) tag:221 image:nil title:@""];
        rightButton.layer.masksToBounds=YES;
        [rightButton setImage:[UIImage imageNamed:@"jiantou_right@2x"] forState:UIControlStateNormal];
        rightButton.layer.cornerRadius=leftButton.width/2;
        rightButton.backgroundColor=[UIColor whiteColor];
        rightButton.alpha=0.8;
        [photoView addSubview:rightButton];
    }
    
//    //图片信息背景
//    UIView *titleView=[[UIView alloc]initWithFrame:CGRectMake(20, IPHONE_HEIGHT-(35+50), IPHONE_WIDTH-40, 50)];
//    titleView.alpha=0.8;
//    titleView.userInteractionEnabled=NO;
//    titleView.backgroundColor=[UIColor blackColor];
//    [photoView addSubview:titleView];
//    
//    //地点
//    UILabel *addressLabel=[MyControl creatLabelWithFrame:CGRectMake(60, titleView.y+5, titleView.width-120, 20) text:[NSString stringWithFormat:@"地点:%@",address]];
//    addressLabel.font=FONT_13;
//    addressLabel.textColor=[UIColor whiteColor];
//    //计算高度
//    CGFloat addressHeight=[LZXHelper textHeightFromTextString:addressLabel.text width:addressLabel.width fontSize:13]+3;
//    addressLabel.height=addressHeight;
//    [photoView addSubview:addressLabel];
//    //时间
//    UILabel *timeLabel=[MyControl creatLabelWithFrame:CGRectMake(60, addressLabel.y+addressLabel.height, titleView.width-120, 20) text:[NSString stringWithFormat:@"时间:%@",time]];
//    timeLabel.textColor=[UIColor whiteColor];
//    timeLabel.font=FONT_13;
//    [photoView addSubview:timeLabel];
//    titleView.height=30+addressHeight;
}

#pragma mark -照片查看取消
- (void)cancelPhotoClick:(UIButton *)button{
    [button removeFromSuperview];
}

#pragma mark -查看照片向左按钮
- (void)leftPhotoClick:(UIButton *)button{
    _photoPageCount--;
    UIButton *photoButton=(UIButton *)button.superview;
    UIScrollView *scrolleView=(UIScrollView *)[photoButton viewWithTag:180];
    //滚动照片
    scrolleView.contentOffset=CGPointMake(_photoPageCount*IPHONE_WIDTH, 0);
    UIButton *leftButton=(UIButton *)[photoButton viewWithTag:220];
    UIButton *rightButton=(UIButton *)[photoButton viewWithTag:221];
    //    if (_photoPageCount==_photoNum) {
    //        rightButton.hidden=YES;
    //    }else{
    rightButton.hidden=NO;
    //    }
    if (_photoPageCount==0) {
        
        leftButton.hidden=YES;
    }else{
        leftButton.hidden=NO;
    }
}

#pragma mark -异常说明
- (void)creatSignInExplainViewWithStr:(NSString *)str{
    NSArray *titleArr=@[@"原因说明",@"请假",@"公出",@"不说明"];
    SignInExplainView *explain=[[SignInExplainView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT) listModel:self.dutyListModel titleArr:titleArr titleStr:str];
    explain.homeController=self;
    [[[UIApplication sharedApplication].delegate window] addSubview:explain];
}

#pragma mark -查看照片向右按钮
- (void)rightPhotoClick:(UIButton *)button{
    _photoPageCount++;
    UIButton *photoButton=(UIButton *)button.superview;
    UIScrollView *scrolleView=(UIScrollView *)[photoButton viewWithTag:180];
    //滚动照片
    scrolleView.contentOffset=CGPointMake(_photoPageCount*IPHONE_WIDTH, 0);
    UIButton *rightButton=(UIButton *)[photoButton viewWithTag:221];
    UIButton *leftButton=(UIButton *)[photoButton viewWithTag:220];
    //    if (_photoPageCount==0) {
    //        leftButton.hidden=YES;
    //    }else{
    leftButton.hidden=NO;
    //    }
    if (_photoPageCount==_photoNum-1) {
        rightButton.hidden=YES;
    }else{
        rightButton.hidden=NO;
    }
}


#pragma mark- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _detailListModel.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SIgnInDetailListModel *model=_detailListModel.dataArr[indexPath.section];
    NSString *cellID=@"SignInDetailTableViewCell";
    SignInDetailTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell=[[SignInDetailTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        __weak SingInDetailViewController *mySelf=self;
        cell.myBlock=^(SIgnInDetailListModel *model){
            if ([model.eventStatus isEqualToString:@"3"]) {
                TaskDetailViewController *detail=[TaskDetailViewController new];
                //detail.jobState=self.jobState;
                detail.businessCode=model.businessCode;
                detail.vacateBillId=model.vacateBillId;
                //detail.sex=model.empSex;
                detail.isOperate=@"0";
                [mySelf.navigationController pushViewController:detail animated:YES];
            }else if([model.eventStatus isEqualToString:@"1"]){
                NSString *titleStr=model.eventCode;
                [mySelf creatSignInExplainViewWithStr:titleStr];
            }
        };
    }
    [cell setCellInfoWithModel:model];
//    //0 拍照签到 5wifi签到
    if ([model.way isEqualToString:@"0"]) {
        //如果有照片
        if (model.photoList.length>0) {
            //保存照片的信息
            //去掉前面的|
            if ([[model.photoList substringToIndex:1]isEqualToString:@"|"]) {
                model.photoList=[model.photoList substringFromIndex:1];
            }
            //去掉最后面的|
            if ([[model.photoList substringFromIndex:model.photoList.length-1]isEqualToString:@"|"]) {
                model.photoList =[model.photoList substringToIndex:model.photoList.length-1];
            }
            //切割字符串
            NSArray *infoArr=[model.photoList componentsSeparatedByString:@"|"];
            cell.photoImageView.urlStr=model.photoList;
//            cell.photoImageView.nameStr=model.signInPlace;
//            cell.photoImageView.timeStr=model.eventTime;
            [cell.photoImageView setImageWithURL:[NSURL URLWithString:infoArr.count>0?infoArr[0]:@""]placeholderImage:[UIImage imageNamed:@"ic_pic_bg@2x"]];
            [cell.photoImageView addTarget:self action:@selector(photoImageView:)];
        }else{
            cell.photoImageView.image=[UIImage imageNamed:@"k_ic_1paizhao@2x"];
        }
    }else if([model.way isEqualToString:@"5"]){
        cell.photoImageView.image=[UIImage imageNamed:@"k_ic_1wifi@2x"];
    }else if([model.way isEqualToString:@"1"]){
        cell.photoImageView.image=[UIImage imageNamed:@"k_ic_1nfc@2x"];
    }
    return cell;

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    SIgnInDetailListModel *model=_detailListModel.dataArr[indexPath.section];
//    //待办
//    if ([model.eventState isEqualToString:@"2"]) {
//        return 126;
//    }else if([model.eventState isEqualToString:@"3"]){
//        if (model.result.length>0) {
//            return 66;
//        }else{
//            return 41;
//        }
//    }else{
        return 66;
//    }
}

#pragma mark -签到详情列表

- (void)getSigninOrSignoutListRequest{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM"];
    //以时间为照片命名
    NSString *timestamp = [formatter stringFromDate:[NSDate date]];
    NSDictionary *dict=@{
                         @"strDate":timestamp,
                         @"strType":self.typeStr?self.typeStr:@"1"
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    //__weak DutyListViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getSigninOrSignoutList soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        _detailListModel=[[SIgnInDetailListModel alloc]initWithResponse:responseObject];
        if ([_detailListModel.code isEqualToString:@"200"]) {
            [_tableView reloadData];
        }else if([_detailListModel.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:_detailListModel.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
